from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import db

from simplenote import Simplenote
import os

from util import *

class dbRecipe(db.Model):
    name = db.StringProperty()
    source = db.StringProperty()
    ingredients = db.TextProperty()
    directions = db.TextProperty()
    tags = db.StringProperty()

def loadRecipe(recipeId):
    key = db.Key.from_path('dbRecipe', long(recipeId))
    recipe = db.get(key)
    return recipe

class EditRecipe(webapp.RequestHandler):
    def get(self):
        myUser = MyUser()
        if not myUser.canEdit:
            self.redirect("/recipes")

        if self.request.get('id'):
            recipe = loadRecipe(self.request.get('id'))
        else:
            recipe = dbRecipe()
            recipe.name = ""
            recipe.source = ""
            recipe.ingredients = ""
            recipe.directions = ""
            recipe.put()
            
        pagePath = []
        pagePath.append(PageDir("opskrifter", "recipes"))
        pagePath.append(PageDir(recipe.name + ": EDIT", ""))

        template_values = {
            'recipe': recipe,
            'path': pagePath,
            'fgColor': "\"#FFFFFF\"",
            'user': MyUser()
        }
        path = os.path.join(os.path.dirname(__file__), 'editRecipe.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        myUser = MyUser()
        if not myUser.canEdit:
            self.redirect("/recipes")

        recipe = loadRecipe(self.request.get('myid').strip())
        name = self.request.get('name').strip()
        if name:
            recipe.name = self.request.get('name').strip()
            recipe.source = self.request.get('source').strip()
            recipe.ingredients = self.request.get('ingredients').strip()
            recipe.directions = self.request.get('directions').strip()
            key = recipe.put()
        else:
            recipe.delete()
        self.redirect("/recipe?id="+str(recipe.key().id()))

class DeleteRecipe(webapp.RequestHandler):
    def get(self):
        myUser = MyUser()
        if not myUser.canEdit:
            self.redirect("/recipes")

        self.response.out.write(self.request.get('ok'))
        recipe = loadRecipe(self.request.get('id').strip())
        if not self.request.get('ok'):
            pagePath = []
            pagePath.append(PageDir("opskrifter", "recipes"))
            pagePath.append(PageDir(recipe.name + ": DELETE", ""))
            path = os.path.join(os.path.dirname(__file__), 'confirmRecipeDelete.html')
            template_values = {
                'recipe': recipe,
                'path': pagePath,
                'user': MyUser()
            }
            self.response.out.write(template.render(path, template_values))
        else:
            recipe.delete()
            self.redirect("/recipes")

class ShowRecipe(webapp.RequestHandler):
    def get(self):
        recipe = loadRecipe(self.request.get('id'))

        pagePath = []
        pagePath.append(PageDir("opskrifter", "recipes"))
        pagePath.append(PageDir(recipe.name, ""))

        recipe.ingredients = recipe.ingredients.replace("\n", "<br>")
        recipe.directions = recipe.directions.replace("\n", "<br>")
        
        template_values = {
            'recipe': recipe,
            'path': pagePath,
            'user': MyUser()
        }
        path = os.path.join(os.path.dirname(__file__), 'recipe.html')
        self.response.out.write(template.render(path, template_values))

class ShowRecipes(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()

        userCanEdit = False
        if user:
            userCanEdit = (user.nickname() == "thomas.the.red")

        pagePath = []
        pagePath.append(PageDir("opskrifter", ""))

        recipes = db.GqlQuery("SELECT * FROM dbRecipe ORDER BY name")

        for r in recipes:
            if not r.name:
                r.delete()

        template_values = {
            'recipes': recipes,
            'path': pagePath,
            'user': MyUser()
        }
        path = os.path.join(os.path.dirname(__file__), 'recipes.html')
        self.response.out.write(template.render(path, template_values))

class RecipeLink:
    def __init__(self):
        self.link = ""
        self.text = ""
        self.source = ""

class RecipeLinkGroup:
    def __init__(self):
        self.headline = ""
        self.links = []

class ShowRecipeLinks(webapp.RequestHandler):
    def get(self):
        simplenote = Simplenote("thomas.the.red@gmail.com", "32hej32")
        note = simplenote.get_note(u'agtzaW1wbGUtbm90ZXINCxIETm90ZRjEsOYGDA')
        data = note[0]["content"].split("\n")

        group = None
        recipeLinkGroups = []
        for line in data[2:]:
            if not line.strip():
                continue
            d = line.split(", ")
            recipeLink = RecipeLink()
            if len(d) > 2:
                recipeLink.text = d[0]
                recipeLink.source = d[1]
                recipeLink.link = d[2]
            else:
                text = line.strip()
                if text[-1] == ":":
                    if group != None:
                        recipeLinkGroups.append(group)
                    group = RecipeLinkGroup()
                    group.headline = text[:-1]
                    continue
                else:
                    recipeLink.text = text
            group.links.append(recipeLink)

        pagePath = []
        pagePath.append(PageDir("links til opskrifter", ""))

        template_values = {
            'recipeLinkGroups': recipeLinkGroups,
            'path': pagePath
        }
        path = os.path.join(os.path.dirname(__file__), 'recipeLinks.html')
        self.response.out.write(template.render(path, template_values))

